package br.client;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import br.common.Leilao;
import br.common.padraoobserver.RemoteObserver;

public class LeilaoClient implements RemoteObserver {

	private Leilao leilaoServer;
	
	public LeilaoClient(){
		try {
			UnicastRemoteObject.exportObject(this);
			this.getLeilaoServer().registerObserver(this);
        }
        catch(Exception re) {
            re.printStackTrace();
        }
	}
	
	public Leilao getLeilaoServer(){
		if (leilaoServer != null)
			return leilaoServer;
		try {			
			System.setSecurityManager(new RMISecurityManager());
			this.leilaoServer = (Leilao) Naming.lookup("rmi://" + getIPServer() + "/leilao");			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return leilaoServer;		
	}
	
	private String getIPServer() {
		try {
			BufferedReader reader =  new BufferedReader(
					new FileReader(System.getProperty("user.dir") + File.separator + "IPServer.txt"));
			return reader.readLine();
		} catch (Exception e) {
			return "localhost";
		}		
	}
	
	public void atualizaLances() throws RemoteException{
		System.out.println("Novo lance: " + this.getLeilaoServer().retornaUltimoLance());
	}
	
	public void fazLance(int a) throws RemoteException{
		System.out.println("fazendo lance: " + a);
		this.getLeilaoServer().lance(a);
	}
	
	@Override
	public void update(String reference) throws RemoteException {
		if(reference.equals("atualizaLances"))
			this.atualizaLances();

	}

}
